/*
 * Created on 2010-9-6
 * Copyright 2008 by Springs Design Inc. All Rights Reserved
 *
*/

package net.xfok.file;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import android.content.Context;

/**
 * @author YangHua
 *
 */
public class FileUtil {
	
	public static final int BUFFER=4096;
	
	public static void writeFile(String content,String filePath){
		try{
			FileWriter fw=new FileWriter(filePath);
			fw.write(content);
			fw.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void writeFile(String content,String filePath,String charset){
		try {
			OutputStreamWriter out = new OutputStreamWriter(
					new FileOutputStream(filePath), charset);			
			out.write(content);
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static String readFile(String filePath){
		StringBuffer sb=new StringBuffer();
		try{
			FileReader fr = new FileReader(filePath);
			int i=0;
			while((i=fr.read())!=-1){
				sb.append((char)i);
			}
			fr.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		return sb.toString();
	} 
	
	public static String readFile(String filePath,String charset){
		StringBuffer sb=new StringBuffer();
		try {
			InputStreamReader read = new InputStreamReader (new FileInputStream(filePath),charset);
			BufferedReader reader=new BufferedReader(read);
			String line;
			while ((line=reader.readLine()) != null) {
				sb.append(line).append("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	} 
	
	public static String readFile(String filePath,int offset,int size){
		String str=null;
		try{
			RandomAccessFile r = new RandomAccessFile(filePath, "r");
			r.seek(offset);
			byte[] bs = new byte[size];
			r.read(bs);
			str=new String(bs);
		}catch(Exception e){
			e.printStackTrace();
		}
		return str;
	}

	public static boolean delFile(String path){
		try {
			File file = new File(path);
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] files = file.list();
				for (int i = 0; i < files.length; i++) {
					File delFile = new File(path + File.separator + files[i]);
					if (!delFile.isDirectory()) {				
						delFile.delete();					
					} else if (delFile.isDirectory()) {
						delFile(path + File.separator + files[i]);
					}
				}
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public static List<File> readFiles(String path) throws FileNotFoundException, IOException {
		List<File> list=new ArrayList<File>();
		try {
			File file = new File(path);
			list.add(file);
			if (file.isDirectory()) {
				String[] fileList = file.list();
				for (int i = 0; i < fileList.length; i++) {
					File readfile = new File(path + File.separator + fileList[i]);
					if (!readfile.isDirectory()) {
						list.add(readfile);
					} else if (readfile.isDirectory()) {
						readFiles(path + File.separator + fileList[i]);
					}
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}
	
	public static List<File> listFiles(String path) throws FileNotFoundException, IOException {
		List<File> list=new ArrayList<File>();
		try {
			File file = new File(path);
			if (file.isDirectory()) {
				String[] fileList = file.list();
				for (int i = 0; i < fileList.length; i++) {
					File readfile = new File(path + File.separator + fileList[i]);
					list.add(readfile);
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}

	public static void zip(String zipPath,String zipFilePath){
		 try {
			OutputStream os = new FileOutputStream(zipFilePath);
			BufferedOutputStream bs = new BufferedOutputStream(os);
			ZipOutputStream zo = new ZipOutputStream(bs);
			zip(zipPath, new File(zipPath), zo, true, true);
			zo.closeEntry();
			zo.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    public static void zip(String path, File basePath, ZipOutputStream zo, boolean isRecursive, boolean isOutBlankDir) throws IOException {
      
        File inFile = new File(path);
        File[] files = new File[0];
        if(inFile.isDirectory()) {    //是目录
            files = inFile.listFiles();
        } else if(inFile.isFile()) {    //是文件
            files = new File[1];
            files[0] = inFile;
        }
        byte[] buf = new byte[1024];
        int len;
        for(int i=0; i<files.length; i++) {
            String pathName = "";
            if(basePath != null) {
                if(basePath.isDirectory()) {
                    pathName = files[i].getPath().substring(basePath.getPath().length()+1);
                } else {
                    pathName = files[i].getPath().substring(basePath.getParent().length()+1);
                }
            } else {
                pathName = files[i].getName();
            }
            if(files[i].isDirectory()) {
                if(isOutBlankDir && basePath != null) {    
                    zo.putNextEntry(new ZipEntry(pathName+"/")); 
                }
                if(isRecursive) {
                    zip(files[i].getPath(), basePath, zo, isRecursive, isOutBlankDir);
                }
            } else {
                FileInputStream fin = new FileInputStream(files[i]);
                zo.putNextEntry(new ZipEntry(pathName));
                while((len=fin.read(buf))>0) {
                    zo.write(buf,0,len);
                }
                fin.close();
            }
        }
    }
    
    public static void unZip(String zipFileName,String outputDirectory) {   
        try {   
            ZipFile zipFile = new ZipFile(zipFileName);   
            Enumeration e = zipFile.getEntries();   
            ZipEntry zipEntry = null;  
            mkDirs(outputDirectory);
            while (e.hasMoreElements()){   
                zipEntry = (ZipEntry)e.nextElement();   
                //System.out.println("unziping "+zipEntry.getName());   
                if (zipEntry.isDirectory()){   
                    String name=zipEntry.getName();   
                    name=name.substring(0,name.length()-1);        
                    mkDirs(outputDirectory+File.separator+name);                       
                    //System.out.println("创建目录："+outputDirectory+File.separator+name);   
                }else{   
                    String name=zipEntry.getName(); 
                    if(name.contains("/")){
                        String dir = name.substring(0,name.lastIndexOf("/")); 
                        mkDirs(outputDirectory+File.separator+dir); 
                    }
                    //System.out.println("创建文件："+outputDirectory+File.separator+name);                     
                    File f=new File(outputDirectory+File.separator+zipEntry.getName());   
                    f.createNewFile();   
                    InputStream in = zipFile.getInputStream(zipEntry);   
                    FileOutputStream out=new FileOutputStream(f);                      
                    int c;   
                    byte[] by=new byte[1024];   
                    while((c=in.read(by)) != -1){   
                        out.write(by,0,c);   
                    }   
                    out.close();   
                    in.close();   
                }   
            }   
        }   
        catch (Exception ex){     
            ex.printStackTrace();   
        }   
    }   
    
    public static void mkDirs(String dir) throws Exception{ 
    	try{
	        if(dir == null || dir.equals("")) return;   
	        File f1 = new File(dir);   
	        if(!f1.exists())   
	            f1.mkdirs();   
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    } 
    
    public static InputStream String2InputStream(String str){
    	ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
    	return stream;
    }

	public static String inputStream2String(InputStream is){
	   BufferedReader in = new BufferedReader(new InputStreamReader(is));
	   StringBuffer buffer = new StringBuffer(BUFFER);
	   try{
		   String line = "";	   
		   while ((line = in.readLine()) != null){
		       buffer.append(line);
		   }
	   }catch(Exception e){
		   e.printStackTrace();
	   }
	   return buffer.toString();
	}
	
	public static void copy(Context context,String from,String to,int n){
		byte[] buffer = new byte[BUFFER];
		int bytes_read;
		InputStream is;	
		try{
			File saveFile=new File(to);
			FileOutputStream os = new FileOutputStream(saveFile);
			if(n>0){
				for(int i=1;i<n;i++){
					is = context.getAssets().open(from+"-"+i);	
					while ((bytes_read = is.read(buffer)) != -1){						
						os.write(buffer, 0, bytes_read);
					}		
				}
			}else{
				is = context.getAssets().open(from);
				while ((bytes_read = is.read(buffer)) != -1){
					os.write(buffer, 0, bytes_read);
				}
				is.close();
				os.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static boolean move(File srcFile, String destPath) {
		// Destination directory
		File dir = new File(destPath);
		// Move file to new directory
		boolean success = srcFile.renameTo(new File(dir, srcFile.getName()));
		return success;
	}

	public static boolean move(String srcFile, String destPath) {
		// File (or directory) to be moved
		File file = new File(srcFile);
		// Destination directory
		File dir = new File(destPath);
		// Move file to new directory
		boolean success = file.renameTo(new File(dir, file.getName()));
		return success;
	}

	public static void copy(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(oldPath);
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[BUFFER];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void copy(File oldfile, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			// File oldfile = new File(oldPath);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(oldfile);
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[BUFFER];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
